import requests
import json
import os
import sys
import pyperclip
from PIL import Image

'''该程序需要联网利用api来压缩图片'''
URL = 'https://api.tinify.com/shrink'

'''此处填写你在tinify网站上申请的apikey'''
APIKEY = 'LzNsMGq0LB7cRMC1cJhFnTrr5D86TN7h'


def getNewPic(picpath):
    
    session = requests.Session()
    session.auth = ('api', APIKEY)
    picdata = open(picpath, 'rb').read()
    re = session.request('POST', URL, data=picdata)
    print(re.text)
    picurl = json.loads(re.text)['output']['url']
    newpicdata = requests.get(picurl).content
    os.remove(picpath)
    dstpath = picpath+picpath[-4:]
    with open(picpath, 'wb') as pic:
        pic.write(newpicdata)
    return picurl


def compress(picpath):
    # 获取文件名
    picpath = os.path.abspath(picpath)
    if picpath.endswith('.bmp'):
        print('无法压缩BMP格式文件', picpath)
        if input('按回车则转化为png格式进行压缩') == '':
            Image.open(picpath).save(picpath.replace('.bmp', '_格式转换.png'))
            picpath = picpath.replace('.bmp', '_格式转换.png')
        else:
            return
    pyperclip.copy(getNewPic(picpath))
    print(pyperclip.paste())


def main(*path):
    for picpath in path:
        compress(picpath)


if __name__ == '__main__':
    args = sys.argv[1:]
    if args:  # 尝试以拖拽在py文件上运行的文件路径执行函数，可批量拖拽处理
        print('导入文件', *(f for f in args))
        main(*args)
    else:  # 否则直接输入或读取剪切板
        path = input('原图片路径，回车读取剪切板：\n')
        while path == '':
            try:
                path = pyperclip.paste()
            except BaseException:
                path = input('输入路径：\n')
        main(path)
    print('完成')
